<?php
namespace frontend\Components;
use yii\web\Application;
use yii\base\Behavior;
use common\models\Signup;

class RulesoBehavior extends Behavior
{

    public function events()
    {
        return [
            Application::EVENT_BEFORE_ACTION => 'beforeAction',
        ];
    }

    public function beforeAction($event)
    {
        //验证用户是否关注
        $this->isFocus();
        //验证用户一天只投一次
        $this->isVote();

        //验证总数是否已满
        $this->isCount();


    }


    //验证报名人数小于50
    public function isCount()
    {
        $count = Signup::find()->count();
        if($count >= 50){
            \Yii::$app->params['isvote'] = [
                'status' => '0',
                'message' => '50名额已满!'
            ];

        }
    }


    //验证是否投过票
    static function isVote()
    {
        $log = Signup::find()
            ->where(['openid' => \Yii::$app->params['userinfo']['openid']])
            ->one();
        if($log){
            //设置后台投票是否通过
            \Yii::$app->params['isvote'] = [
                'status' => '0',
                'message' => '您已报名，不用再次报名!'
            ];
        }

        //return $log;

    }

    //验证是否关注
    static function isFocus()
    {
        $session = \Yii::$app->session;
        $res = \Yii::$app->wechat->getUserInfo($session['access_token']['openid']);
        if($res['subscribe'] !== 1){
            \Yii::$app->params['isfocus'] = '0';
            //设置后台投票是否通过
            \Yii::$app->params['isvote'] = [
                'status' => '0',
                'message' => '您未关注，请关注后再来投票!'
            ];
        }
    }


}
